"""
成绩管理模块序列化器
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import GradeDetail


class GradeStudentSerializer(serializers.ModelSerializer):
    """学生信息序列化器（用于成绩）"""
    student_id = serializers.CharField(source='profile.student_id', read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'student_id']


class GradeDetailSerializer(serializers.ModelSerializer):
    """成绩详情序列化器"""
    student = GradeStudentSerializer(read_only=True)
    student_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = GradeDetail
        fields = [
            'id', 'student', 'student_id', 'course_no', 'course_name',
            'grade', 'time', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class GradeListSerializer(serializers.ModelSerializer):
    """成绩列表序列化器（简化版）"""
    student_id = serializers.SerializerMethodField(read_only=True)
    student_name = serializers.SerializerMethodField(read_only=True)
    major_name = serializers.SerializerMethodField(read_only=True)
    class_name = serializers.SerializerMethodField(read_only=True)
    
    class Meta:
        model = GradeDetail
        fields = ['id', 'student_id', 'student_name', 'major_name', 'class_name', 'course_name', 'grade', 'time']
    
    def get_student_id(self, obj):
        """获取学号（优先从Profle获取，其次使用username）"""
        if obj.student:
            if hasattr(obj.student, 'profile') and obj.student.profile and obj.student.profile.student_id:
                return obj.student.profile.student_id
            return obj.student.username  # 如果没有profile，返回username作为学号
        return None
    
    def get_student_name(self, obj):
        """获取学生姓名"""
        if obj.student:
            return obj.student.first_name or obj.student.username
        return None
    
    def get_major_name(self, obj):
        """获取专业名称"""
        if obj.student and hasattr(obj.student, 'profile') and obj.student.profile:
            return obj.student.profile.major or '-'
        return '-'
    
    def get_class_name(self, obj):
        """获取班级名称"""
        if obj.student and hasattr(obj.student, 'profile') and obj.student.profile:
            return obj.student.profile.class_name or '-'
        return '-'
